package com.bwie.filter;

import io.jsonwebtoken.Jwts;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @Author: tsh
 * @Date: 2025/7/18 14:14
 * @Description: TODO
 **/
@Configuration
@Order(-1)
public class MyGlobalFilter implements GlobalFilter {
    @Autowired
    StringRedisTemplate stringRedisTemplate;
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        String url = request.getURI().getPath();
        if(url.contains("/login")||url.contains("/sendCode/")||url.contains("/userReg")){
            System.out.println("白名单:"+url);

            //放行
            return chain.filter(exchange);
        }
        String token = request.getHeaders().getFirst("token");
        if(token==null){
            System.out.println("token为空:"+url);
            //返回401
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }

        Integer userId = Jwts.parser().setSigningKey("123456").parseClaimsJws(token).getBody().get("userId", Integer.class);

        String key="token-"+userId;
        String tokenKey = stringRedisTemplate.opsForValue().get(key);
        if(tokenKey==null){
            System.out.println("token过期:"+url);
            //返回401
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        if(!token.equals(tokenKey)){
            System.out.println("token错误:"+url);
            //返回401
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        //token续期
        stringRedisTemplate.expire(tokenKey,60, TimeUnit.MINUTES);
        return chain.filter(exchange);
    }
}
